<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Event;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderController extends Controller
{
    /**
     * 获取所有订单（可以添加分页和筛选）
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        // 只返回当前用户的订单，明确使用sanctum guard
        $orders = Order::where('user_id', Auth::guard('sanctum')->id())->with('event')->get();
        return response()->json($orders);
    }

    /**
     * 获取单个订单
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $order = Order::where('id', $id)->where('user_id', Auth::guard('sanctum')->id())->with('event')->first();
        if ($order) {
            return response()->json($order);
        } else {
            return response()->json(['error' => 'Order not found'], 404);
        }
    }

    /**
     * 创建新订单
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'event_id' => 'required|exists:events,id',
            'quantity' => 'required|integer|min:1',
        ]);

        // 获取事件信息计算总价
        $event = Event::find($validated['event_id']);
        $totalAmount = $event->price * $validated['quantity'];

        $order = Order::create([
            'user_id' => Auth::guard('sanctum')->id(),
            'event_id' => $validated['event_id'],
            'quantity' => $validated['quantity'],
            'total_amount' => $totalAmount,
            'status' => 'pending',
        ]);

        // 加载关联的事件信息
        $order->load('event');

        return response()->json($order, 201);
    }

    /**
     * 更新订单
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $order = Order::where('id', $id)->where('user_id', Auth::guard('sanctum')->id())->first();
        if (!$order) {
            return response()->json(['error' => 'Order not found'], 404);
        }

        $validated = $request->validate([
            'status' => 'sometimes|required|string|in:pending,paid,cancelled',
            'quantity' => 'sometimes|required|integer|min:1',
        ]);

        // 如果更新数量，重新计算总价
        if (isset($validated['quantity'])) {
            $event = Event::find($order->event_id);
            $validated['total_amount'] = $event->price * $validated['quantity'];
        }

        $order->update($validated);
        $order->load('event');
        return response()->json($order);
    }

    /**
     * 删除订单
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $order = Order::where('id', $id)->where('user_id', Auth::guard('sanctum')->id())->first();
        if (!$order) {
            return response()->json(['error' => 'Order not found'], 404);
        }

        $order->delete();
        return response()->json(['message' => 'Order deleted successfully']);
    }
}